<!--
 * @Author: zhao 13370229059@163.com
 * @Date: 2024-04-22 12:07:40
 * @LastEditors: zhao 13370229059@163.com
 * @LastEditTime: 2024-07-31 10:10:46
 * @FilePath: \work\pages\index\components\work.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <uv-modal ref="modalRef" asyncClose showCancelButton title="报工" :width="modalWidth" @close="onClose" @confirm="onConfirm">
    <view class="box">
      <uv-form labelPosition="left" ref="formRef" labelWidth="120" :model="model" :rules="rules" class="form">
        <uv-form-item label="工序：" prop="task_status_id" borderBottom>
          <uv-picker ref="taskPicker" keyName="name" :columns="columns.tasks" @confirm="val => confirm(val, 'task_status_id')"></uv-picker>
          <view class="tips" v-if="!model.task_status_id" @click="picker(taskPicker)">请选择</view>
          <view v-else @click="picker(taskPicker)">{{ model.task.name }}</view>
        </uv-form-item>
        <uv-form-item label="报工人：" prop="member_id" borderBottom @click="showSexSelect">
          <view class="tips" v-if="!model.member_id" @click="picker(memberPicker)">请选择</view>
          <view v-else @click="picker(memberPicker)">{{ model.member.name }}</view>
        </uv-form-item>
        <uv-form-item label="用时（小时）：" prop="hour" borderBottom>
          <uv-input v-model="model.hour" type="digit"> </uv-input>
        </uv-form-item>
        <uv-form-item label="完成数量：" prop="quantity" borderBottom>
          <uv-input v-model="model.quantity" type="digit"> </uv-input>
        </uv-form-item>
        <uv-form-item label="报工日期：" prop="produce_date" borderBottom>
          <uv-datetime-picker ref="produceDatePicker" v-model="model.produce_date" mode="date" @confirm="val => confirm(val, 'produce_date')">
          </uv-datetime-picker>
          <view class="tips" v-if="!model.produce_date" @click="picker(produceDatePicker)">请选择</view>
          <view v-else @click="picker(produceDatePicker)">{{ model.produce_date }}</view>
        </uv-form-item>
        <uv-form-item label="图片：" borderBottom>
          <uv-upload
            :fileList="files.list"
            :previewFullImage="false"
            :previewFullVideo="false"
            :maxCount="1"
            @afterRead="afterRead"
            @delete="deletePic"
          ></uv-upload>
        </uv-form-item>
        <uv-form-item label="备注：" prop="note" borderBottom>
          <uv-textarea v-model="model.note" :maxlength="-1" autoHeight placeholder="请输入内容"></uv-textarea>
        </uv-form-item>
        <uv-form-item label="工序单价：" prop="price" borderBottom>
          <uv-input v-model="model.price" type="digit" placeholder="请输入内容"></uv-input>
        </uv-form-item>
      </uv-form>
    </view>
    <popupHttp :data="columns.members" ref="memberPicker" @onSuccess="val => confirm(val, 'member_id')"></popupHttp>
  </uv-modal>
  <uv-toast ref="toastRef"></uv-toast>
</template>

<script setup>
  import { ref, reactive, watch, defineProps, defineEmits, nextTick, getCurrentInstance } from 'vue';
  import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js';
  import { baseURL } from '@/static/common.js';
  import store from '@/store/index.js'; //需要引入store
  let { state, commit } = store;
  let modalWidth = ref(1000);
  let modalRef = ref(),
    taskPicker = ref(),
    formRef = ref(),
    memberPicker = ref(),
    produceDatePicker = ref(),
    toastRef = ref(),
    columns = reactive({
      tasks: [],
      members: []
    });
  let emits = defineEmits(['update:modelValue']);
  let props = defineProps({
    modelValue: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {};
      }
    }
  });
  let model = reactive({
    member_id: '',
    member: {},
    task: {},
    task_status_id: '',
    quantity: undefined,
    hour: '0',
    produce_date: '',
    note: '',
    price: 0
  });
  let rules = reactive({
    task_status_id: {
      type: 'number',
      required: true,
      message: '请选择工序',
      trigger: ['blur', 'change']
    },
    member_id: {
      type: 'number',
      required: true,
      message: '请选择报工人',
      trigger: ['blur', 'change']
    },
    hour: {
      type: 'string',
      required: true,
      message: '请输入报工用时',
      trigger: ['blur', 'change']
    },
    quantity: {
      type: 'string',
      required: true,
      message: '请输入数量',
      trigger: ['blur', 'change']
    },
    price: {
      type: 'number',
      required: true,
      message: '请输入工序单价',
      trigger: ['blur', 'change']
    }
  });
  const httpOptions = async () => {
    let { members, tasks } = await uni.$uv.http.post('product_schedules/options', {
      product_id: props.data.id
    });
    // 设置工序数据，设置员工数据
    columns.tasks = [tasks];
    columns.members = members;

    //1.1 若我在这个订单里面是某个数量节点的负责人
    // 取我是负责人的第一个未完成的数量节点。
    //2.1 若我不是这个订单里任何数量任务的负责人。
    // 取第一个未完成的数量节点。
    // 先取出未完成的节点，因为不管是什么情况，都是要未完成的。
    let arr = tasks.filter(r => r.status === 'incomplete');
    if (!arr.length) return;
    let val = arr.find(r => r.officers.find(row => row.id === state.vuex_user.current_member));
    if (val) {
      model.task_status_id = val.id;
      model.task = val;
    } else {
      model.task_status_id = arr[0].id;
      model.task = arr[0];
    }
  };
  let files = reactive({
    list: []
  });
  // 监听
  watch(
    () => props.modelValue,
    async val => {
      if (!val && formRef.value) {
        formRef.value.resetFields();
        files.list = [];
        model.task = {};
        return;
      }
      if (modalRef.value) {
        await httpOptions();
        // 默认赋值
        model.produce_date = dayjs().format('YYYY-MM-DD');
        let member_id = state.vuex_user.current_member;
        model.member_id = member_id;
        model.member = {
          id: member_id,
          name: columns.members.find(r => r.id === member_id).name
        };
        let index = columns.members.findIndex(r => r.id === member_id);
        columns.members[index].active = true;
        modalRef.value.open();
        uni.getSystemInfo({
          success: ({ windowWidth }) => {
            modalWidth.value = windowWidth * 0.8;
          }
        });
      }
    },
    { immediate: true }
  );
  const onClose = () => {
    emits('update:modelValue', false);
  };
  const picker = val => {
    val.open();
  };
  const confirm = (val, key) => {
    if (key === 'member_id') {
      model.member_id = val[0].id;
      model.member = val[0];
    } else if (key === 'produce_date') {
      nextTick(() => {
        model.produce_date = dayjs(val.value).format('YYYY-MM-DD');
      });
    } else if (key === 'task_status_id') {
      model.task_status_id = val.value[0].id;
      model.task = val.value[0];
    }
  };
  // 提交接口
  const httpSave = async () => {
    await uni.$uv.http.post('product_schedules/save', {
      ...model,
      product_id: props.data.id,
      tracking_id: props.data.order_id,
      image_path: files.list.length && files.list[0].url,
      image_name: files.list.length && files.list[0].name
    });
    toastRef.value.show({
      message: '保存成功',
      type: 'success'
    });
    modalRef.value.close();
  };
  // 提交表单
  const onConfirm = () => {
    formRef.value
      .validate()
      .then(() => {
        httpSave();
      })
      .catch(errors => {
        modalRef.value.closeLoading();
      });
  };
  // 新增图片
  let afterRead = async event => {
    files.list.push({
      ...event.file,
      status: 'uploading',
      message: '上传中',
      url: ''
    });
    let { url } = await uni.$uv.http.upload('attachments/upload_file', {
      filePath: event.file.url,
      name: 'file',
      formData: {
        current_org: state.vuex_user.current_org,
        auth_token: state.vuex_user.auth_token,
        current_member: state.vuex_user.current_member
      }
    });
    let file = files.list[0];
    file.status = 'success';
    file.message = '已完成';
    file.url = url;
  };
  const deletePic = () => {
    files.list = [];
  };
</script>

<style lang="scss" scoped>
  .box {
    height: 60vh;
    overflow-y: auto;
    width: 100%;
    .form {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;
      ::v-deep .uv-form-item {
        width: 45%;
      }
    }
  }
  .tips {
    color: #ccc;
  }
</style>
